package com.example.demo.api;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.demo.data.WeiboUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xcx
 * @date 2023/2/18 18:51
 */
@Slf4j
@Controller
public class WeiBoController {
    @RequestMapping("/weibo/login")
    public String login() {
        return "login";
    }

    @RequestMapping("/weibo/success")
    public String authorize(String code, HttpSession session) throws Exception {
        // 使用code换取token，换取成功则继续，否则重定向登录页
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("client_id", "1145439904");
        paramMap.put("client_secret", "95f985a1d8355b9117ea29a111b613d1");
        paramMap.put("grant_type", "authorization_code");
        paramMap.put("redirect_uri", "https://www.xingchenxu.top/auth/weibo/success");
        paramMap.put("code", code);
        String url = this.buildUrl("https://api.weibo.com", "/oauth2/access_token", paramMap);
        //发送post请求换取token
        HttpResponse httpResponse = HttpRequest.post(url)
                .timeout(20000)//超时，毫秒
                .execute();

        Map<String, String> errors = new HashMap<>();
        if (httpResponse.getStatus() == 200) {
            String body = httpResponse.body();
            log.info("body: {}", body);
            WeiboUser weiboUser = JSONUtil.toBean(body, WeiboUser.class);
            // TODO 使用 weiboUser.getUid() 查询数据库 若查询结果为null，则之前未登陆过，查询其社交信息进行注册
            Boolean selectUser = true;
            if (selectUser) {
                log.info("用户未注册，查询用户信息进行注册");
                this.register(weiboUser);

                // 获取粉丝信息
                this.getFan(weiboUser);
            } else {
                log.info("用户已注册，更新相关信息");
                // TODO 更新TOKEN、UID、登录过期时间等信息
                weiboUser.getAccess_token();
                weiboUser.getUid();
                weiboUser.getExpires_in();
            }

            // 将用户信息返回
            session.setAttribute("userInfo", weiboUser.toString());
            return "home";
        } else {
            errors.put("msg", "获得第三方授权失败，请重试");
            session.setAttribute("errors", errors);
            return "login";
        }
    }


    @RequestMapping("/weibo/fail")
    public void authorize() {
        log.info("weibo fail...");
    }


    /**
     * 获取用户信息
     */
    public void register(WeiboUser weiboUser) {
        Map<String, Object> selectUserParam = new HashMap<>();
        selectUserParam.put("access_token", weiboUser.getAccess_token());
        selectUserParam.put("uid", weiboUser.getUid());
//      String selectUserUrl = this.buildUrl("https://api.weibo.com", "/2/users/show.json", selectUserParam);

        HttpResponse execute = HttpRequest.get("https://api.weibo.com/2/users/show.json").form(selectUserParam).timeout(2000).execute();
        if (execute.getStatus() == 200) {
            String userInfo = execute.body();
            log.info("userInfo: {}", userInfo);
            //TODO 调用微博api接口获取用户信息，然后进行注册,记录以下值
            weiboUser.getAccess_token();
            weiboUser.getUid();
            weiboUser.getExpires_in();
            weiboUser.setUserInfo(userInfo);
        }
    }

    /**
     * 获取
     */
    public void getFan(WeiboUser weiboUser) {
        Map<String, Object> selectUserParam = new HashMap<>();
        selectUserParam.put("access_token", weiboUser.getAccess_token());
        selectUserParam.put("uid", weiboUser.getUid());
//      String selectUserUrl = this.buildUrl("https://api.weibo.com", "/2/users/show.json", selectUserParam);

        HttpResponse execute = HttpRequest.get("https://api.weibo.com/2/friendships/followers.json").form(selectUserParam).timeout(2000).execute();
        if (execute.getStatus() == 200) {
            String fanList = execute.body();
            log.info("粉丝信息: {}", fanList);
            weiboUser.setFans(fanList);
        }
    }


    /**
     * 构建请求URl地址
     *
     * @return
     */
    private static String buildUrl(String host, String path, Map<String, Object> querys) throws
            UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(host).append(path);

        StringBuilder sbQuery = new StringBuilder();

        for (Map.Entry<String, Object> query : querys.entrySet()) {
            if (sbQuery.length() > 0) {
                sbQuery.append("&");
            }
            sbQuery.append(query.getKey());
            sbQuery.append("=");
            sbQuery.append(URLEncoder.encode(query.getValue().toString(), "utf-8"));
        }

        if (sbQuery.length() > 0) {
            sbUrl.append("?").append(sbQuery);
        }

        return sbUrl.toString();
    }
}
